package com.itany.shop.service.impl;

import com.itany.shop.dao.ItemDao;
import com.itany.shop.dao.OrderDao;
import com.itany.shop.dao.impl.OrderDaoImpl;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.User;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserNotLoginException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.OrderService;
import com.itany.shop.util.ParameterUtil;
import com.itany.shop.vo.Cart;

import java.util.List;

/**
 * @author 石小俊
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = (OrderDao) ObjectFactory.getObject("orderDao");
    private ItemDao itemDao = (ItemDao) ObjectFactory.getObject("itemDao");

    @Override
    public String createNo(Cart cart, User user) throws UserNotLoginException {
        if (cart == null || user == null) {
            throw new UserNotLoginException("请先登录");
        }

        // 结算功能主要是同时保存订单以及订单中的明细信息
        // 涉及到一个订单与多个明细的多表保存操作
        // 1.先保存订单,返回自动生成的主键值
        Order order = new Order();
        // 生成订单号
        String no = ParameterUtil.createNo();
        order.setNo(no);
        order.setUser(user);
        order.setPrice(cart.getPrice());

        Integer id = orderDao.insertReturnPrimaryKey(order);
        // 将返回的主键赋值给当前订单对象
        order.setId(id);

        // 2.遍历购物车中所有明细,每一条明细对应一条保存操作
        List<Item> items = cart.getItems();
        for (Item item : items) {
            // 此时购物车中的明细都存在对应的商品、数量、总价信息
            // 只需要将所属订单赋值给当前明细即可
            item.setOrder(order);
            // 每遍历一条明细,保存一条明细记录
            itemDao.insertItem(item);
        }
        return no;
    }

    @Override
    public List<Order> findMyOrders(User user) throws UserNotLoginException {
        if (user == null) {
            throw new UserNotLoginException("请先登录");
        }
        return orderDao.selectByUserId(user.getId());
    }

    @Override
    public Order findDetail(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        return orderDao.selectDetailById(Integer.parseInt(id));
    }
}
